package cn.wgx.study.rabbitmq;

import cn.wgx.study.rabbitmq.config.RabbitConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Slf4j
@Component
@RabbitListener(queues = {RabbitConfig.QUEUE_A, RabbitConfig.QUEUE_B,
        RabbitConfig.QUEUE_C, RabbitConfig.QUEUE_D})
public class MQProducer implements RabbitTemplate.ConfirmCallback {


    //由于rabbitTemplate的scope属性设置为ConfigurableBeanFactory.SCOPE_PROTOTYPE，所以不能自动注入
    private RabbitTemplate rabbitTemplate;

    /**
     * 构造方法注入rabbitTemplate
     */
    @Autowired
    public MQProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
        rabbitTemplate.setConfirmCallback(this); //rabbitTemplate如果为单例的话，那回调就是最后设置的内容
    }

    //发送消息
    public void sendMsg(String content) {
        CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
        //把消息放入ROUTINGKEY_A对应的队列当中去，对应的是队列A
        log.info("正在发送消息A通道: " + content);
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_A, RabbitConfig.ROUTINGKEY_A, content +"A", correlationId);
        log.info("正在发送消息B通道: " + content);
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_B, null, content+"B", correlationId);
        log.info("正在发送消息C通道: " + content);
        rabbitTemplate.convertAndSend(RabbitConfig.EXCHANGE_C, "spring.ioc", content+"C", correlationId);

    }


    //接受消息并处理
    @RabbitHandler
    public void process(String content) {
        log.info("接收到消息： " + content);
    }


    //处理完消息回调
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
//        log.info(" 回调id:" + correlationData);
        if (ack) {
            log.info("消息成功消费,回调id:{}" , correlationData);
        } else {
            log.info("消息消费失败,原因:{}, 回调id:{}", cause, correlationData);
        }
    }
}
